package com.useeinfo.oa.open.admin.maintaining;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.FacilityCatBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.FacilityCat;
import com.useeinfo.oa.modules.maintaining.biz.FacilityMaintainSnapBiz;
import com.useeinfo.oa.modules.maintaining.biz.MaintainDataBiz;
import com.useeinfo.oa.modules.maintaining.biz.MaintainTechnologyBiz;
import com.useeinfo.oa.modules.maintaining.entity.FacilityMaintainSnap;
import com.useeinfo.oa.modules.maintaining.entity.MaintainData;
import com.useeinfo.oa.modules.maintaining.entity.MaintainTechnology;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;

@Controller
@RequestMapping("/web/admin/maintainTechnology")
public class MaintainTechnologyAction {
    @Autowired
    private MaintainTechnologyBiz maintainTechnologyBiz;
    @Autowired
    private MaintainDataBiz maintainDataBiz;


    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private FacilityMaintainSnapBiz facilityMaintainSnapBiz;

    private final static Logger logger = LoggerFactory.getLogger(MaintainTechnologyAction.class);

    private Workbook wb;
    private Sheet sheet;
    private Row row;


    @RequestMapping("/list")
    public ModelAndView list(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/maintainTechnology/list");
        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "searchName", required = false) String searchName,
                               @RequestParam(value = "facilityCatId", required = false) String facilityCatId,//传此参数 表示此快照表和工艺的设备类型要一致
                               HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("searchName", searchName);
        if (StringUtils.isNotBlank(facilityCatId)) {
            queryParam.getSqlMap().put("facilityCatId", facilityCatId);
        }
        JSONObject jsonObject = maintainTechnologyBiz.findJSONList(queryParam);
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            Long catId = json.getLong("facilityCatId");
            json.put("rootCatName", "");
            if (catId != null) {
                FacilityCat rootCat = facilityCatBiz.findRootCat(catId);
                if (rootCat != null) {
                    json.put("rootCatName", rootCat.getCatName());
                }
            }
        }
        return jsonObject;
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        MaintainTechnology maintainTechnology = maintainTechnologyBiz.findModel(StringConverters.ToLong(id));
        Long timeStamp = System.currentTimeMillis();
        modelAndView.addObject("timeStamp", timeStamp);
        modelAndView.addObject("maintainTechnology", maintainTechnology);
        String rootCatId = "";
        if (maintainTechnology != null && maintainTechnology.getFacilityCat() != null) {
            FacilityCat rootCat = facilityCatBiz.findRootCat(maintainTechnology.getFacilityCat().getId());
            rootCatId = rootCat.getId() + "";
        }
        modelAndView.addObject("rootCatId", rootCatId);
        modelAndView.setViewName("pages/admin/maintainTechnology/edit");
        return modelAndView;
    }

    /**
     * 获取编辑页面（复制新增）
     */
    @RequestMapping("/copyEditPage")
    public ModelAndView copyEditPage(@RequestParam(value = "id", required = false) String id, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        MaintainTechnology oldMaintainTechnology = maintainTechnologyBiz.findModel(StringConverters.ToLong(id));
        MaintainTechnology newMaintainTechnology = new MaintainTechnology();
        if (oldMaintainTechnology != null) {
            newMaintainTechnology.setName(oldMaintainTechnology.getName());
            // 维保内容添加过来
            newMaintainTechnology.setMaintainDataContent(oldMaintainTechnology.getMaintainDataContent());
            newMaintainTechnology.setFacilityCat(oldMaintainTechnology.getFacilityCat());
            newMaintainTechnology.setOrganization(oldMaintainTechnology.getOrganization());
            newMaintainTechnology.setPrepareWork(oldMaintainTechnology.getPrepareWork());
            newMaintainTechnology.setEstimateTime(oldMaintainTechnology.getEstimateTime());
            newMaintainTechnology.setEffective(oldMaintainTechnology.getEffective());
            newMaintainTechnology.setSafetyRequirement(oldMaintainTechnology.getSafetyRequirement());
            newMaintainTechnology.setRequireMaterials(oldMaintainTechnology.getRequireMaterials());
            newMaintainTechnology.setRequireTools(oldMaintainTechnology.getRequireTools());
            newMaintainTechnology.setRequireSkill(oldMaintainTechnology.getRequireSkill());
            newMaintainTechnology.setDescription(oldMaintainTechnology.getDescription());
            newMaintainTechnology.setEnterprise(oldMaintainTechnology.getEnterprise());
        }
        Long timeStamp = System.currentTimeMillis();
        modelAndView.addObject("timeStamp", timeStamp);
        modelAndView.addObject("oldId", oldMaintainTechnology.getId()+"");
        modelAndView.addObject("maintainTechnology", newMaintainTechnology);
        String rootCatId = "";
        if (newMaintainTechnology.getFacilityCat() != null) {
            FacilityCat rootCat = facilityCatBiz.findRootCat(oldMaintainTechnology.getFacilityCat().getId());
            rootCatId = rootCat.getId() + "";
        }
        modelAndView.addObject("rootCatId", rootCatId);
        modelAndView.setViewName("pages/admin/maintainTechnology/edit");

        return modelAndView;
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeEdit")
    @ResponseBody
    public ResultDto executeEdit(MaintainTechnology maintainTechnology,
                                 @RequestParam(value = "timeStamp", required = false) String timeStamp,
                                 @RequestParam(value = "oldId", required = false) String oldId,
                                 @RequestParam(value = "selectCatId[]", required = false) List<String> selectCatIds,
                                 @RequestParam(value = "selectRootCatId[]", required = false) List<String> selectRootCatIds,
                                 @RequestParam(value = "selectOrganizationId[]", required = false) List<String> selectOrganizationIds,
                                 HttpServletRequest request) {
        MaintainTechnology oldMaintainTechnology;
        if(!StringUtils.isEmpty(oldId)){
             oldMaintainTechnology = maintainTechnologyBiz.findModel(Long.valueOf(oldId));
        }else{
            oldMaintainTechnology=new MaintainTechnology();
        }

        if (!StringUtils.isBlank(oldId)) {
            maintainTechnology.setMaintainDataContent(oldMaintainTechnology.getMaintainDataContent());
            maintainTechnology.setFacilityCat(oldMaintainTechnology.getFacilityCat());
            maintainTechnology.setOrganization(oldMaintainTechnology.getOrganization());
            maintainTechnology.setPrepareWork(oldMaintainTechnology.getPrepareWork());
            maintainTechnology.setEstimateTime(oldMaintainTechnology.getEstimateTime());
            maintainTechnology.setEffective(oldMaintainTechnology.getEffective());
            maintainTechnology.setSafetyRequirement(oldMaintainTechnology.getSafetyRequirement());
            maintainTechnology.setRequireMaterials(oldMaintainTechnology.getRequireMaterials());
            maintainTechnology.setRequireTools(oldMaintainTechnology.getRequireTools());
            maintainTechnology.setRequireSkill(oldMaintainTechnology.getRequireSkill());
            maintainTechnology.setDescription(oldMaintainTechnology.getDescription());
            maintainTechnology.setEnterprise(oldMaintainTechnology.getEnterprise());
        }

        if (StringUtils.isBlank(timeStamp)) {
            return ResultUtil.error("参数异常");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise == null) {
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        if (selectRootCatIds != null && selectCatIds == null && maintainTechnology.getMaintainDataContent() == null) {
            return ResultUtil.error("请选择设备类型，或取消选择设备专业");
        }
        if (CollectionUtils.isNotEmpty(selectCatIds)) {
            maintainTechnology.setFacilityCat(facilityCatBiz.findModel(StringConverters.ToLong(selectCatIds.get(0))));
        } else if (CollectionUtils.isNotEmpty(selectCatIds) && oldMaintainTechnology.getFacilityCat() != null) {
            maintainTechnology.setFacilityCat(oldMaintainTechnology.getFacilityCat());
        }
        if (CollectionUtils.isNotEmpty(selectOrganizationIds)) {
            maintainTechnology.setOrganization(organizationBiz.findModel(StringConverters.ToLong(selectOrganizationIds.get(0))));
        } else {
            return ResultUtil.error("请选择部门");
        }
        //查看有没有维保内容,如果没有 则无法新增
        QueryParam queryParamT = new QueryParam();
        queryParamT.getSqlMap().put("timeStamp", timeStamp);
        queryParamT.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        List<MaintainData> maintainDataListT = maintainDataBiz.findList(queryParamT);
        if (maintainTechnology.getId() == null) {

            if (CollectionUtils.isEmpty(maintainDataListT)) {
                return ResultUtil.error("请添加至少一个维保内容");
            }
        } else {
            QueryParam queryParamO = new QueryParam();
            queryParamO.getSqlMap().put("maintainTechnologyId", maintainTechnology.getId() + "");
            queryParamO.getSqlMap().put("enterpriseId", enterprise.getId() + "");
            List<MaintainData> maintainDataListO = maintainDataBiz.findList(queryParamO);
            if (CollectionUtils.isEmpty(maintainDataListT) && CollectionUtils.isEmpty(maintainDataListO)) {
                return ResultUtil.error("请添加至少一个维保内容");
            }
        }

//        if (maintainTechnology.getId() == null && CollectionUtils.isEmpty(maintainDataListT)) {
//            return ResultUtil.error("请添加至少一个维保内容");
//        }
        if (maintainTechnology.getId() == null) {
            //新增 分配一个流水号
            maintainTechnology.setCode(maintainTechnologyBiz.getCode(enterprise.getId() + ""));
        }
        maintainTechnology.setEnterprise(enterprise);
        maintainTechnologyBiz.addOrUpdate(maintainTechnology);
        //给本次添加的维保内容绑定ID
        for (MaintainData maintainData : maintainDataListT) {
            maintainData.setMaintainTechnology(maintainTechnology);
            maintainDataBiz.addOrUpdate(maintainData);
        }
        //清空无效维保内容
        maintainDataBiz.deleteUselessData();
        //添加快照
        JSONArray jsonArray = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainTechnologyId", maintainTechnology.getId() + "");
        List<MaintainData> maintainDataList = maintainDataBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(maintainDataList)) {
            for (MaintainData maintainData : maintainDataList) {
                JSONObject jsonObject = maintainData.toJSONObject2();
                jsonArray.add(jsonObject);
            }
        }
        if (oldId == null && "".equals(oldId)) {
            maintainTechnology.setMaintainDataContent(jsonArray.toString());
        }

        maintainTechnologyBiz.addOrUpdate(maintainTechnology);
        return ResultUtil.success();
    }

    /**
     * 删除工艺
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id, HttpServletRequest request) {
        MaintainTechnology maintainTechnology = maintainTechnologyBiz.findModel(StringConverters.ToLong(id));
        if (maintainTechnology != null) {
            maintainTechnologyBiz.deleteLogic(maintainTechnology);
        }
        return ResultUtil.success();
    }


    /**
     * 上传导入文件
     */
    @RequestMapping("/uploadTechnologyImportFile")
    @ResponseBody
    public ResultDto uploadTechnologyImportFile(HttpServletRequest request,
                                                @RequestParam(value = "file", required = false) MultipartFile file) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            return ResultUtil.error("当前用户企业信息有误，请退出重新登录");
        }
        if (null != file && !file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf("."));
            try {
                InputStream is = file.getInputStream();
                if (".xls".equals(ext)) {
                    wb = new HSSFWorkbook(is);
                } else if (".xlsx".equals(ext)) {
                    wb = new XSSFWorkbook(is);
                } else {
                    return ResultUtil.error("请导入正确格式的文件（Excel）");
                }
            } catch (Exception e) {
                logger.error("IOException", e);
                return ResultUtil.error("导入失败，请刷新后重试");
            }
        }
        ResultDto resultDto = maintainTechnologyBiz.checkData(wb,enterprise);
        if (resultDto.getStatus() != 0) {
            return resultDto;
        }
        ThreadUtils.importMaintainTechnologyThread(maintainTechnologyBiz, wb, enterprise);
        return ResultUtil.success();
    }

    @RequestMapping("/importPage")
    public ModelAndView importPage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.setViewName("pages/admin/maintainTechnology/import");
        return modelAndView;
    }
}
